package com.hdjd.filter;

import com.hdjd.entities.Account;
import com.hdjd.entities.Admin;
import com.hdjd.entities.School;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 刘子强
 * 2021/2/2 19:07
 */
@WebFilter(value = "*.jsp")     //只拦截 jsp 请求
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("account");
        Admin admin = (Admin) session.getAttribute("admin");
        School school = (School) session.getAttribute("school");

        //获得项目虚拟路径
        String path = request.getContextPath();
        //获得当前请求路径
        String url = request.getRequestURI();

        //过滤非法用户  //只拦截了 jsp 请求
        if(url.indexOf("login.jsp") != -1 || url.indexOf("register.jsp") != -1 ){   //如果是登录页面请求或者是注册页面请求，则通过继续执行
            filterChain.doFilter(request, response);
        }else if(account != null || admin != null || school != null){         //如果请求中带有session相关数据，表示用户已登录，则通过继续执行
            filterChain.doFilter(request, response);
        }else{                                          //否则，都跳转到 登录页面
            response.sendRedirect(path + "/login.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
